package com.ruoyi.jacExcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.github.pagehelper.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.easyExcel.EasyExcelListenerFactory;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jacExcel.domain.Test2;
import com.ruoyi.jacExcel.service.ISysUserService;
import com.ruoyi.jacExcel.service.ITest2Service;
import com.ruoyi.jacExcel.util.EasyExcelTool;
import com.ruoyi.system.domain.SysUser;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Slf4j
@Controller
public class JacExcelController extends BaseController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITest2Service test2Service;


//    @GetMapping("/exports")
//    @ResponseBody
//    @ApiOperation(value = "get export",notes = "test")
//    public void exports(SysUser user, HttpServletResponse response, HttpServletRequest request) {
////        if (regulationCountry.getDeptid() == null || regulationCountry.getDeptid() == "") {
////            regulationCountry.setDeptid("101");
////        }
////        Class<?> clazz = domain.getClass();
////        clazz.getDeclaredMethod(clazz.getName())
//
//        try {
//            String filename = UUID.randomUUID().toString() + "_" + ".xlsx";
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            response.setHeader("Content-Disposition",
//                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
//            List<SysUser> list = sysUserService.selectUserList(user);
//            ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
//            util.exportExcel(list, "country",response.getOutputStream());
//        } catch (Exception e) {
//            log.error("下载文件失败", e);
//        }
//    }
//
//    @PostMapping("/importData")
//    @ResponseBody
//    @ApiOperation(value = "post import",notes = "test")
//    public String importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
//        List<SysUser> userList = util.importExcel(file.getInputStream());
//        String message = sysUserService.importFile(userList, updateSupport);
//        return message;
//    }
//
//    @GetMapping("/importTemplate")
//    @ResponseBody
//    @ApiOperation(value = "get importtemple",notes = "test")
//    public void importTemplate(HttpServletResponse response, HttpServletRequest request)
//    {
//        try {
//            String filename = "用户导入模板.xlsx";
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("multipart/form-data");
//            response.setHeader("Content-Disposition",
//                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
//            ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
//            util.importTemplateExcel("用户",response.getOutputStream());
//        } catch (Exception e) {
//            log.error("下载文件失败", e);
//        }
//    }

    @PostMapping("/imp")
    @ResponseBody
    public void imp(MultipartFile file) throws IOException {
        List<Test2> list = new ArrayList<>();//此list用来存储导入文件中的每行数据
        EasyExcelListenerFactory<Test2> tf = new EasyExcelListenerFactory<>(list);
        AnalysisEventListener listener = tf.getListener();
        EasyExcel.read(file.getInputStream(),Test2.class,listener).sheet().doRead();//执行完此句后list内就存了文件中数据

        for (Test2 t:list){
            test2Service.insertTest2(t);//实际导入过程，可以根据自身情况进行相应导入成功失败判断，并返回给前台
        }

    }

    @GetMapping("/exp")
    @ResponseBody
    public void exp(HttpServletResponse response) throws IOException {
        List<Test2> list = test2Service.selectTest2List(new Test2()); //被导出数据本身，这里的list只是测试，具体业务可能要进行筛选
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=test.xlsx");
        EasyExcel.write(response.getOutputStream(), Test2.class).registerWriteHandler(EasyExcelTool.getStyleStrategy()).sheet("模板1").doWrite(list);//‘模板1’可根据业务内容自行变更
    }

    @GetMapping("/bigdataexp")
    @ResponseBody
    public void bigdataexp(HttpServletResponse response) throws IOException {

        // 这里 需要指定写用哪个class去写
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=test.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), Test2.class).build();
        // 这里注意 如果同一个sheet只要创建一次
        WriteSheet writeSheet = EasyExcel.writerSheet("模板").build();
        List<Test2> data = null;

        int pageNumber =1;
        boolean flag = true;
        while (flag){
            startPageBySelf(pageNumber,10000);
            data = test2Service.selectTest2List(new Test2());
            excelWriter.write(data, writeSheet);
            if(data==null || data.size()<10000){
                flag=false;
            }
            pageNumber++;
        }


        // 千万别忘记finish 会帮忙关闭流
        excelWriter.finish();
    }

    @GetMapping("/importTemplate")
    @ResponseBody
    @ApiOperation(value = "get importtemple",notes = "test")
    public void importTemplate(HttpServletResponse response, HttpServletRequest request)
    {
        try {
            String filename = "xx导入模板.xlsx";
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, filename));
            ExcelUtil<Test2> util = new ExcelUtil<>(Test2.class);
            util.importTemplateExcel("用户",response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

}

